<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        width: 600px;
        height: 600px;
        border: 1px solid;
        position: relative;
        margin: 0 auto;
      }

      .container div {
        width: 180px;
        height: 180px;
        background: gray;
        position: absolute;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <div style="left: 10px; top: 10px"></div>
      <div style="left: 33.33%; top: 10px"></div>
      <div style="left: 66.66%; top: 10px"></div>

      <div style="left: 10px; top: 33.33%"></div>
      <div style="left: 33.33%; top: 33.33%"></div>
      <div style="left: 66.66%; top: 33.33%"></div>

      <div style="left: 10px; top: 66.66%"></div>
      <div style="left: 33.33%; top: 66.66%"></div>
      <div style="left: 66.66%; top: 66.66%"></div>
    </div>
    <script>
      var colorArr = [
        "yellow",
        "blue",
        "black",
        "pink",
        "skyblue",
        "purple",
        "orange",
        "green",
        "plum",
      ];
      var divs = document.querySelectorAll(".container div");
      divs.forEach(function (div, key) {
        div.style.backgroundColor = colorArr[key];
        div.onmousedown = function (e) {
          var x = e.clientX - this.offsetLeft;
          var y = e.clientY - this.offsetTop;
          this.style.zIndex = 10;
          this.onmousemove = function (e) {
            var xx = e.clientX;
            var yy = e.clientY;
            this.style.left = xx - x + "px";
            this.style.top = yy - y + "px";
          };

          document.onmouseup = function () {
            console.log(div);
            div.onmousemove = "";
            div.style.zIndex = 0;
          };
        };
      });
    </script>
  </body>
</html>
